package com.renli.controller;

import com.renli.bean.ResultJson;
import com.renli.pojo.Login;
import com.renli.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    private LoginService loginService;


    @RequestMapping("/loginToken")
    @ResponseBody
    public ResultJson loginToken(String username, String password) {
        System.out.println("loginToken");
        String msg = "";
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            token.setRememberMe(true);
            try {
                subject.login(token);
                String loginToken = UUID.randomUUID().toString();
                if (loginService.saveToken(username, loginToken)) {
                    return new ResultJson().setSuccess("登录成功", loginToken);
                } else {
                    return new ResultJson<>().setFail("网络异常,请稍后重试(redis无法访问)");
                }

            } catch (IncorrectCredentialsException ice) {
                msg = "用户名/密码不匹配！";
            } catch (LockedAccountException lae) {
                msg = "账户已被冻结！";
            } catch (UnknownAccountException uae) {
                msg = "账户不存在";
            } catch (AuthenticationException ae) {
                System.out.println("================" + ae);
                msg = ae.getMessage();
            }
        }
        return new ResultJson<>().setFail(msg);
    }


    @RequestMapping("/login")
    public String login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                token.setRememberMe(true);
                subject.login(token);
                return "redirect:index.jsp";
            } catch (AuthenticationException e) {
                System.out.println("登录失败");
                e.printStackTrace();
            }
        }
        return "error";
    }


    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @RequestMapping("/toSuccess")
    public String success(String username, String password) {

        return "success";
    }

    //    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @RequestMapping("/reg")
    public String reg(Login login) {
//        次数使用的方法和shiro验证时的方法一致，所有需要 加密算法 和加密次数 与 realm中 credentialsMatcher 属性中配置的算法和次数相同（在配置文件spring_shiro.xml中的配置）
        SimpleHash md5 = new SimpleHash("md5", login.getPassword(), login.getUsername(), 32);
        System.out.println(md5);
        login.setPassword(md5.toString());
        if (loginService.add(login) == 1) {
            return "success";
        }
        return "error";
    }

}
